﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Linq;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Resources;
using System.Globalization;

using ZetaPrints.ZetaClient.Business;
using ZetaPrints.ZetaClient.Data;
using ZetaPrints.ZetaClient.Data.Repository.Linq;
using ZetaPrints.ZetaClient.Shared;
using ZetaPrints.ZetaClient.Shared.Manipulator;

namespace ZetaPrints.ZetaClient.Presentation
{
    internal enum OrderDetailGridColumns:int
    {
        Name = 0, 
        Value = 1,
        Id = 2
    }

    internal enum PictureChoice
    {
        Downloading,
        NoPicture,
        DownloadFailed
    }

    internal enum OrderHeaderGridColumns:int
    {
        OrderId = 0,
        OrderNumber = 1,
        CreatedBy = 2,
        Created = 3,
        Balance = 4,
        OrderStatus = 5,
        SiteName = 6
    }


    public partial class FormMain : Form
    {
        #region private attributes
        /// <summary>
        /// This is used to keep on a loop and update things on status
        /// every so often checking how things are going
        /// </summary>
        private Thread _timeTicker;
        /// <summary>
        /// This is the business manager, tha main screen of the system
        /// </summary>
        private ZetaManager _zetaManager;
        /// <summary>
        /// This is the screen to take care of the management of sites
        /// </summary>
        private FormSiteManagement _formSiteManagement;
        /// <summary>
        /// Form for the download date and time
        /// </summary>
        private FormDownloadDate _formDownloadDate;
        /// <summary>
        /// This is the order selected
        /// </summary>
        private OrderManager _currentOrderManager;
        /// <summary>
        /// The last column that was sorted
        /// </summary>
        private int _lastColumnIndexSorted;
        /// <summary>
        /// The order in which the column was sorted
        /// </summary>
        private bool _lastColumnInvertedSorted;
        /// <summary>
        /// This is the current picture that is selected
        /// on the grid.
        /// </summary>
        private int _currentPicturePreviewIndex;
        #endregion


        #region delegate
        /// <summary>
        /// delegate the updat ethe OrderHeader Control
        /// </summary>
        /// <param name="toolStripComboBoxSiteEnable"></param>
        /// <param name="toolStripButtonDownloadEnabled"></param>
        /// <param name="toolStripButtonStopDownloadEnabled"></param>
        delegate void UpdateChangeOrderHeaderControl(bool toolStripComboBoxSiteEnable,
            bool toolStripButtonDownloadEnabled);
        /// <summary>
        /// delegate to update the OrderDetail Control
        /// </summary>
        /// <param name="toolStripButtonDownloadOrderFilesEnabled"></param>
        /// <param name="toolStripButtonStopDownloadOrderFilesEnabled"></param>
        delegate void UpdateChangeOrderDetailControl(
            bool toolStripButtonDownloadOrderFilesEnabled,
            bool toolStripButtonStopDownloadOrderFilesEnabled);
        /// <summary>
        /// This updates the one button folder
        /// </summary>
        /// <param name="toolStripButtonOrderDetailFolderEnabled"></param>
        delegate void UpdateChangeOrderDetailFolder(
            bool toolStripButtonOrderDetailFolderEnabled);
        /// <summary>
        /// This is a generic delegate to be used when no parameters are necessary
        /// </summary>
        delegate void NoParameterDelegate();
        /// <summary>
        /// The delegate to update the status bar
        /// </summary>
        delegate void ToolStripStatusLabelTextDelegate(string message);
        /// <summary>
        /// This returns true if the current selected delegate is a file
        /// </summary>
        /// <returns></returns>
        delegate bool CheckIsCurrentTabAFile();
        /// <summary>
        /// Returns the current selected order id
        /// </summary>
        /// <returns></returns>
        delegate Guid GetOrderIdSelectedDelegate();
        /// <summary>
        /// The delegate to get the picture in the palce
        /// </summary>
        /// <param name="image"></param>
        delegate void SetPictureDelegate(Image image);
        /// <summary>
        /// The new status that we got for this entry now has to change on the order header
        /// </summary>
        /// <param name="orderNumber"></param>
        /// <param name="newStatus"></param>
        delegate void ChangeStatusDelegate(int orderNumber, string newStatus);
        #endregion


        #region constructors
        /// <summary>
        /// Start up the main form
        /// </summary>
        public FormMain()
        {
            #region !DEBUG
            try
            {
            #endregion
                InitializeComponent();

                //Thread.CurrentThread.CurrentCulture = new CultureInfo("pt-BR");
                //Thread.CurrentThread.CurrentUICulture = new CultureInfo("pt-BR");

                this.fileToolStripMenuItem.Text = Lang.ManageSites;

                ResourceManager resource =
                new ResourceManager("Wrox.ProCSharp.Localization.Welcome", Assembly.GetExecutingAssembly());


                #region version on top
                string versionText = System.Reflection.Assembly.GetEntryAssembly().GetName().ToString();

                versionText = versionText.Substring(versionText.IndexOf("Version=") + 8);
                versionText = versionText.Substring(0, versionText.IndexOf(','));

                this.Text += "  (version:" + versionText + ")";

#if DEBUG
            this.Text += " DEBUG VERSION";
#endif
                #endregion

                try
                {
                    /// initialize the zeta manager
                    _zetaManager = new ZetaManager();
                }
                catch (InvalidDataException ex)
                {
                    #region InvalidDataException - Database file not found handler for auto recover
                    if (ex.Message.Contains(Lang.DatabaseNotFound))
                    {
                        /// ask if it wants to auto recover
                        switch (MessageBox.Show(this, ex.Message + "\n\r" + Lang.DoYouWantToTryToAutorecover, Lang.DatabaseNotFound, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error))
                        {
                            case DialogResult.Yes:
                                ZetaClientConfiguration zetaClientConfiguration = new ZetaClientConfiguration();

                                string originalDataSource = zetaClientConfiguration.DataSource;

                                if (zetaClientConfiguration.AutoDataSourceRecover())
                                {
                                    try
                                    {
                                        /// initialize the zeta manager
                                        _zetaManager = new ZetaManager();
                                        MessageBox.Show(this, Lang.AutoRecoverSucceed, Lang.AutoRecover, MessageBoxButtons.OK);
                                    }
                                    catch (InvalidDataException ex2)
                                    {
                                        if (ex2.Message.Contains(Lang.DatabaseNotFound))
                                        {
                                            zetaClientConfiguration.DataSource = originalDataSource;
                                            zetaClientConfiguration.Save();
                                            MessageBox.Show(this, Lang.AutoRecoverFailedExitingApplication + "\n\r" + zetaClientConfiguration.DataSource, Lang.AutoRecover, MessageBoxButtons.OK);
                                        }
                                        else
                                        {
                                            throw;
                                        }


                                    }
                                }
                                else
                                {
                                    zetaClientConfiguration.DataSource = originalDataSource;
                                    zetaClientConfiguration.Save();
                                    MessageBox.Show(this, Lang.AutoRecoverFailedExitingApplication + "\n\r" + zetaClientConfiguration.DataSource, Lang.AutoRecover, MessageBoxButtons.OK);
                                }
                                break;
                        }
                    }
                    else
                    {
                        throw;
                    }
                    #endregion
                }

                /// if zetaManager is null that means something went bad
                if (_zetaManager != null)
                {
                    /// messaging system connecting.
                    _zetaManager.OnEventMessenger += new EventHandler<EventMessenger>(_zetaManager_OnEventMessenger);

                    if (!RefreshSiteCheckListBox())
                    {
                        OpenSiteManagement();
                    }

                    /// start the time ticker
                    _timeTicker = new Thread(new ThreadStart(TimeTickerThread));
                    _timeTicker.Start();

                    listViewOrderHeader.ColumnClick += new ColumnClickEventHandler(listViewOrderHeader_ColumnClick);

                    /// when a check changes
                    checkedListBoxSite.ItemCheck += new ItemCheckEventHandler(checkedListBoxSite_ItemCheck);


                    this.dataGridViewOrderDetail.CellClick += new DataGridViewCellEventHandler(dataGridViewOrderDetail_CellClick);
                    this.dataGridViewOrderDetail.CellDoubleClick += new DataGridViewCellEventHandler(dataGridViewOrderDetail_CellDoubleClick);

                    RefreshOrderHeaderDisplay(false);
                    RefreshOrderDetailDisplay(false);

                    toolStripComboBoxOrderStatus.TextChanged += new EventHandler(toolStripComboBoxOrderStatus_TextChanged);
                }
                #region !DEBUG
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.ToString(), "System could not start", MessageBoxButtons.OK);
            }
            #endregion
        }
        #endregion
        

        #region event handlers
        #region main menu
        /// <summary>
        /// Download orders
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void downloadOrdersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_zetaManager.GetSelectedSiteManagerList().Count > 0)
            {
                /// create the form download date dialog
                _formDownloadDate = new FormDownloadDate(_zetaManager.LatestOrderDateTimeOfSelected());
                _formDownloadDate.VisibleChanged += new EventHandler(_formDownloadDate_VisibleChanged);
                _formDownloadDate.ShowDialog(this);
            }
            else
            {
                MessageBox.Show(this, "No site has been selected to download, please select a site and try again", 
                    "No site selected", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }
        /// <summary>
        /// When we click on the button at the main menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenSiteManagement();
        }
        /// <summary>
        /// When the Site Manager is coming down we need to update the database
        /// with the changes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _formSiteManagement_FormClosing(object sender, FormClosingEventArgs e)
        {
            switch (_formSiteManagement.DialogResult)
            {
                case DialogResult.OK:
                case DialogResult.Yes:
                    /// uncheck the sites that we are going to be deleting.
                    foreach (Site siteDelete in _formSiteManagement.SiteDeleteList)
                    {
                        for( int count = 0; count < checkedListBoxSite.Items.Count; count ++)
                        {
                            if( checkedListBoxSite.Items[count].ToString() == siteDelete.SiteName )
                            {
                                if (_currentOrderManager != null)
                                {
                                    /// if the current item selected is part of a delete site, remove it
                                    if (_currentOrderManager.SiteEntry.SiteName == siteDelete.SiteName)
                                    {
                                        _currentOrderManager.AbortAllThreads();
                                        _currentOrderManager = null;
                                    }
                                }
                                checkedListBoxSite.SetItemChecked(count, false);
                                break;
                            }
                        }
                    }
                    /// turn on the refresh sign
                    RefreshOrderHeaderDisplay(true);
                    RefreshOrderDetailDisplay(true);

                    /// refresh the order header display
                    RefreshOrderHeaderGrid();
                    _zetaManager.SaveSites(_formSiteManagement.SiteList);
                    _zetaManager.DeleteSite(_formSiteManagement.SiteDeleteList);
                    RefreshSiteCheckListBox();
                    RefreshOrderHeaderGrid();
                    RefreshOrderDetailArea();
                    break;
            }
        }
        /// <summary>
        /// When we click on the preference button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void siteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormPreferences formPreferences = new FormPreferences();
            formPreferences.ShowDialog(this);
        }
        #endregion
        #region zeta manager
        /// <summary>
        /// Event handler to all the information that comes back from the Business Manager
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _zetaManager_OnEventMessenger(object sender, EventMessenger eventMessenger)
        {
            Guid orderId = new Guid();

            switch( eventMessenger.MessageType )
            {
                case MessageTypeOption.Message:
                    /// just display the text
                    Invoke(new ToolStripStatusLabelTextDelegate(UpdateStripStatusLableText), eventMessenger.MessageString);

                    if( eventMessenger.MessageString.StartsWith("File not found") )
                    {
                        string fileName = eventMessenger.MessageString.Substring(eventMessenger.MessageString.LastIndexOf(':')+1);

                        if (dataGridViewOrderDetail.SelectedCells.Count > 0)
                        {
                            string fileNameSelected = 
                                dataGridViewOrderDetail.Rows[dataGridViewOrderDetail.SelectedCells[0].RowIndex].Cells[(int)OrderDetailGridColumns.Name].Value.ToString();
                            if ((fileName.Contains(fileNameSelected)) || (fileNameSelected.Contains(fileName)))
                            {
                                Invoke(new SetPictureDelegate(SetPicture), new Bitmap(@"Resources\DownloadFailed.jpg"));
                            }
                        }
                    }
                    break;
                case MessageTypeOption.FetchOrdersThread:
                    int siteId = Convert.ToInt32(eventMessenger.MessageString);

                    /// before the refresh make sure this site is displaying right now
                    if (_zetaManager.IsSiteSelected(siteId))
                    {
                        Invoke(new NoParameterDelegate(RefreshOrderHeaderGrid));
                    }
                    break;
                case MessageTypeOption.ChangeOrderStatusThread:
                    orderId = new Guid(eventMessenger.MessageString);

                    /// check to make sure before we start the refresh that
                    /// we have returned the current displayed order
                    if (_currentOrderManager.OrderEntry.OrderId == orderId)
                    {
                        Invoke(new NoParameterDelegate(RefreshOrderDetailArea));
                        Invoke(new ChangeStatusDelegate(ChangeOrderStatus),
                            _currentOrderManager.OrderEntry.OrderNumber,
                            _currentOrderManager.OrderEntry.OrderStatus.OrderStatusName);
                    }                   
                    break;
                case MessageTypeOption.DownloadOrderDetailsThread:
                    orderId = new Guid(eventMessenger.MessageString);

                    /// check to make sure before we start the refresh that
                    /// we have returned the current displayed order
                    if (_currentOrderManager.OrderEntry.OrderId == orderId)
                    {
                        Invoke(new NoParameterDelegate(RefreshOrderDetailArea));
                    }
                    break;
                case MessageTypeOption.FetchOrderFileDetailThread:
                    orderId = new Guid(eventMessenger.MessageString);

                    /// check to make sure before we start the refresh that
                    /// we have returned the current displayed order
                    if (_currentOrderManager.OrderEntry.OrderId == orderId)
                    {
                        Invoke(new NoParameterDelegate(RefreshOrderFileArea));
                    }
                    break;
                case MessageTypeOption.DownloadFileThread:
                    orderId = new Guid(eventMessenger.MessageString);

                    /// check to make sure before we start the refresh that
                    /// we have returned the current displayed order
                    if (_currentOrderManager.OrderEntry.OrderId == orderId)
                    {
                        Invoke(new NoParameterDelegate(RefreshOrderFileArea));
                    }
                    break;
                case MessageTypeOption.Error:
                    MessageBox.Show(this, eventMessenger.MessageString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                default:
                    break;

            }
        }
        #endregion
        #region list view order
        /// <summary>
        /// When we select an item go into a thread system
        /// to fetch the information
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listViewOrderHeader_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewOrderHeader.SelectedItems.Count > 0)
            {
                /// but a wrod in the middle for the user to wait
                RefreshOrderDetailDisplay(true);

                Guid orderId = new Guid(listViewOrderHeader.SelectedItems[0].SubItems[(int)OrderHeaderGridColumns.OrderId].Text);
                string siteName = listViewOrderHeader.SelectedItems[0].SubItems[(int)OrderHeaderGridColumns.SiteName].Text;

                /// if the new order is not the same as the new one, go and clean out the 
                /// detail area
                if (orderId.ToString() != toolStripTextBoxCurrentOrderNumber.Text)
                {
                    ClearOrderDetailArea();

                    SetPicture(PictureChoice.Downloading);

                    _currentPicturePreviewIndex = -1;

                    _currentOrderManager = _zetaManager.GetOrderManager(siteName, orderId);

                    if (_currentOrderManager != null)
                    {
                        /// if we do not have detail download them now.
                        if (!_currentOrderManager.HasDetails)
                        {
                            _currentOrderManager.DownloadOrderDetails(false);
                        }
                        else
                        {
                            RefreshOrderDetailArea();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// When we need to sort the item
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void listViewOrderHeader_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            /// our little trick the on the second click for us to 
            /// invert the sorting
            if (_lastColumnIndexSorted == e.Column)
            {
                /// we switch between them
                if (_lastColumnInvertedSorted)
                {
                    _lastColumnInvertedSorted = false;
                }
                else
                {
                    _lastColumnInvertedSorted = true;
                }
            }
            else
            {
                _lastColumnInvertedSorted = false;
                _lastColumnIndexSorted = e.Column;
            }

            this.listViewOrderHeader.ListViewItemSorter = new ListViewOrderHeaderSorter(e.Column, _lastColumnInvertedSorted);
            this.listViewOrderHeader.Sort();
        }
        #endregion
        #region buttons
        /// <summary>
        /// When the 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _formDownloadDate_VisibleChanged(object sender, EventArgs e)
        {
            /// if the dialog returned with a OK we go ahead and use the date supplied
            switch (_formDownloadDate.DialogResult)
            {
                case DialogResult.OK:
                    RefreshOrderHeaderDisplay(true);
                    _zetaManager.DownloadOrderList(_formDownloadDate.ResultDateTime);
                    break;
            }

            /// only detroy the object if we are invisible
            if (_formDownloadDate.Visible == false)
            {
                /// destroy the form, we do not need it
                /// anymore
                _formDownloadDate.Dispose();
            }
        }
        private void toolStripButtonSiteManagement_Click(object sender, EventArgs e)
        {
            OpenSiteManagement();
        }
        #endregion
        #region siteview
        /// <summary>
        /// There was a change on the selection of the sites
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void checkedListBoxSite_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            checkedListBoxSiteItemCheck(((CheckedListBox)sender).Text, e.NewValue);
        }
        void checkedListBoxSiteItemCheck(string checkItemText, CheckState checkState)
        {
            RefreshOrderHeaderDisplay(true);

            /// did we check or unchecked the entry?
            if (checkState == CheckState.Checked)
            {
                _zetaManager.AddSiteToSelected(checkItemText);
            }
            else if (checkState == CheckState.Unchecked)
            {
                _zetaManager.RemoveSiteFromSelection(checkItemText);

                /// we need to force the delete of the entires now.
                RefreshOrderHeaderGrid();
            }
        }
        #endregion
        #region order detail
        /// <summary>
        /// Gets the current bitmaps for the order
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonDownloadOrderFiles_Click(object sender, EventArgs e)
        {
            /// we assume we do not need to download the file
            bool downloadFiles = true;

            /// we assuem they are all there.
            bool allExist = false;

            /// does our order have ever downloaded any files?
            if (_currentOrderManager.HasLocalFiles)
            {
                /// now we know they do not exist already.
                allExist = true;

                /// we must download without a question.
                downloadFiles = false;
            }

            /// if we already have all the files, why download all of them again?
            if (allExist)
            {
                switch (MessageBox.Show(this, "You are asking to download the files again, would you like for all the files to be downloaded again?", "Download Again", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning))
                {
                    case DialogResult.Yes:
                        downloadFiles = true;
                        break;
                }
            }

            if (downloadFiles)
            {
                _currentOrderManager.DownloadFileDetails(downloadFiles);
            }
        }
        /// <summary>
        /// When we click on the little folder we want to show where the current tab is pointing to.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonOrderDetailFolder_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process prc = new System.Diagnostics.Process();

            string fileName = string.Empty;

            /// find the first path in my path
            foreach (FileManager fileManager in _currentOrderManager.FileManagerList)
            {
                if (fileManager.OrderFileDetailEntry.LocalPath != null)
                {
                    if (fileManager.OrderFileDetailEntry.LocalPath.Length > 0)
                    {
                        fileName = fileManager.OrderFileDetailEntry.LocalPath;
                    }
                }
            }
            
            if (fileName.Length > 0)
            {
                string folderPath = fileName.Substring(0, fileName.LastIndexOf(@"\"));

                System.Diagnostics.Process.Start(folderPath);
            }
        }
        /// <summary>
        /// When we double click we want to open the entry if it is a image
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void dataGridViewOrderDetail_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
             /// did we select a entry that has a picture?
            if (dataGridViewOrderDetail.Rows[e.RowIndex].Cells[(int)OrderDetailGridColumns.Id].Value.ToString().StartsWith("File_"))
            {
                /// we need the information about the file.
                string fileIndex = dataGridViewOrderDetail.Rows[e.RowIndex].Cells[(int)OrderDetailGridColumns.Id].Value.ToString();
                fileIndex = fileIndex.Substring(fileIndex.IndexOf("_") + 1);
                int fileIndexNumber = Convert.ToInt32(fileIndex);

                /// get the file manager
                FileManager fileManager = _currentOrderManager.GetFileManager(fileIndexNumber);

                /// the only condition is if the file exist localy. If not then we go
                /// to the download process
                if (fileManager.FileExistsLocaly)
                {
                    System.Diagnostics.Process.Start(fileManager.OrderFileDetailEntry.LocalPath);
                }
                else
                {
                    SetPicture(PictureChoice.Downloading);
                    /// we do not need to force it because it does not exist
                    fileManager.DownloadFile(false);
                }
            }
        }
        /// <summary>
        /// Check if our action button was clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void dataGridViewOrderDetail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridViewOrderDetail.Rows[e.RowIndex].Cells[(int)OrderDetailGridColumns.Id].Value != null)
            {
                /// did we select a entry that has a picture?
                if (dataGridViewOrderDetail.Rows[e.RowIndex].Cells[(int)OrderDetailGridColumns.Id].Value.ToString().StartsWith("File_"))
                {
                    /// we need the information about the file.
                    string fileIndex = dataGridViewOrderDetail.Rows[e.RowIndex].Cells[(int)OrderDetailGridColumns.Id].Value.ToString();
                    fileIndex = fileIndex.Substring(fileIndex.IndexOf("_") + 1);
                    _currentPicturePreviewIndex = Convert.ToInt32(fileIndex);

                    /// get the file manager
                    FileManager fileManager = _currentOrderManager.GetFileManager(_currentPicturePreviewIndex);

                    /// if the file exists locally lets check what it is
                    if ((fileManager.FileExistsLocaly) && (fileManager.IsImage))
                    {
                        /// put the picture on the screen area
                        this.pictureBoxPreview.Image = fileManager.GetImageThumbnail(pictureBoxPreview.Size.Height, pictureBoxPreview.Size.Width);
                    }
                    else
                    {
                        if (!fileManager.FileExistsLocaly)
                        {
                            SetPicture(PictureChoice.Downloading);
                            /// first time downloading, does not need 
                            /// to know.
                            fileManager.DownloadFile(false);
                        }
                        else
                        {
                            SetPicture(PictureChoice.NoPicture);
                        }
                    }
                }
                else
                {
                    SetPicture(PictureChoice.NoPicture);
                }
            }
        }
        #endregion
        #region order status
        /// <summary>
        /// When we click on the confirm of the order status change
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonChangeOrderStatus_Click(object sender, EventArgs e)
        {
            _currentOrderManager.SetOrderStatus(OrderStatusManipulator.FromLangToCommand(toolStripComboBoxOrderStatus.SelectedText));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void toolStripComboBoxOrderStatus_TextChanged(object sender, EventArgs e)
        {
            /// if the change has changed from the order than enable this button, if not
            /// then we do not enable this button
            if ((_currentOrderManager != null) &&
                (toolStripComboBoxOrderStatus.SelectedItem.ToString() != null) &&
                (_currentOrderManager.OrderEntry.OrderStatus.OrderStatusName != OrderStatusManipulator.FromLangToCommand(toolStripComboBoxOrderStatus.SelectedItem.ToString())))
            {
                toolStripButtonChangeOrderStatus.Enabled = true;
            }
            else
            {
                toolStripButtonChangeOrderStatus.Enabled = false;
            }
        }
        #endregion
        #endregion


        #region private methods
        #region refresh
        /// <summary>
        /// Shows a big refreshing dialog right in the middle of the
        /// order header display
        /// </summary>
        /// <param name="enabled"></param>
        public void RefreshOrderHeaderDisplay(bool visible)
        {
            labelRefreshOrderHeader.Visible = visible;
        }
        /// <summary>
        /// Shows a big refreshing dialog right in the middle of the
        /// order detail display
        /// </summary>
        /// <param name="enabled"></param>
        public void RefreshOrderDetailDisplay(bool visible)
        {
            labelRefreshOrderDetail.Visible = visible;
        }
        #endregion
        #region picture
        /// <summary>
        /// Puts a picutre in the preview area
        /// </summary>
        /// <param name="image"></param>
        private void SetPicture(Image image)
        {
            pictureBoxPreview.Image = image;
        }
        private void SetPicture(PictureChoice pictureChoice)
        {
            try
            {
                switch (pictureChoice)
                {
                    case PictureChoice.DownloadFailed:
                        SetPicture(new Bitmap(@"Resources\DownloadFailed.JPG"));
                        break;
                    case PictureChoice.Downloading:
                        SetPicture(new Bitmap(@"Resources\Downloading.JPG"));
                        break;
                    case PictureChoice.NoPicture:
                        SetPicture(new Bitmap(@"Resources\NoImage.JPG"));
                        break;

                }
            }
            catch
            {
                /// I do not want the application crashing because of something so stupid
                /// as a resource file not there.
            }
        }
        #endregion
        #region update
        /// <summary>
        /// Updates the strip with a new label
        /// </summary>
        /// <param name="message"></param>
        private void UpdateStripStatusLableText(string message)
        {
            toolStripStatusLabelMain.Text = message;
        }
        #endregion
        #region time ticker
        /// <summary>
        /// this is the method to be used on the degate so the 
        /// Ticker thread can manipulate the controls
        /// </summary>
        /// <param name="toolStripButtonDownloadOrderFilesEnabled"></param>
        /// <param name="toolStripButtonStopDownloadOrderFilesEnabled"></param>
        private void ChangeOrderDetailControl(
            bool toolStripButtonDownloadOrderFilesEnabled,
            bool toolStripButtonStopDownloadOrderFilesEnabled
            )
        {
            toolStripButtonDownloadOrderFiles.Enabled = toolStripButtonDownloadOrderFilesEnabled;
            toolStripButtonStopDownloadOrderFiles.Enabled = toolStripButtonStopDownloadOrderFilesEnabled;
        }
        /// <summary>
        /// Changes the DetailFolder and the save button
        /// </summary>
        /// <param name="toolStripButtonOrderDetailFolderEnabled"></param>
        private void ChangeOrderDetailFileControl(bool toolStripButtonOrderDetailFolderEnabled)
        {
            toolStripButtonOrderDetailFolder.Enabled = toolStripButtonOrderDetailFolderEnabled;
        }
        /// <summary>
        /// If the current tab is a file
        /// </summary>
        /// <returns></returns>
        private bool CurrentDetailHasLocalFiles()
        {
            bool currentDetailHasLocalFiles = false;

            if (_currentOrderManager != null)
            {
                currentDetailHasLocalFiles = _currentOrderManager.HasLocalFiles;
            }

            return currentDetailHasLocalFiles;
        }
        /// <summary>
        /// Returns the current header selected
        /// </summary>
        /// <returns></returns>
        private Guid GetOrderIdSelected()
        {
            Guid orderId = new Guid(0,0,0,0,0,0,0,0,0,0,0);

            if ((listViewOrderHeader.SelectedItems != null) && (listViewOrderHeader.SelectedItems.Count > 0))
            {
                orderId = new Guid(listViewOrderHeader.SelectedItems[0].SubItems[(int)OrderHeaderGridColumns.OrderId].Text);
            }

            return orderId;
        }
        /// <summary>
        /// This is the guy that ticks one every 500 milliseconds to 
        /// check the status of the screen.
        /// </summary>
        private void TimeTickerThread()
        {
            /// name the thread
            Thread.CurrentThread.Name = "TimeTickerThread";

            int updateStatusToDone = 5;

            while (true)
            {
                #region order detail
                /// do we have any order details selected?
                if ((toolStripTextBoxCurrentOrderNumber.Text.Length > 0))
                {
                    /// in theory this should never be false,since the current order id 
                    /// text is set
                    if (_currentOrderManager != null)
                    {
                        if (_currentOrderManager.HasFileRecords)
                        {
                            if (_currentOrderManager.AreThreadsAlive)
                            {
                                Invoke(new UpdateChangeOrderDetailControl(ChangeOrderDetailControl), false, true);
                            }
                            else
                            {
                                Invoke(new UpdateChangeOrderDetailControl(ChangeOrderDetailControl), true, false);
                            }
                        }
                        else
                        {
                            Invoke(new UpdateChangeOrderDetailControl(ChangeOrderDetailControl), false, false);
                        }
                    }
                }
                else
                {
                    Invoke(new UpdateChangeOrderDetailControl(ChangeOrderDetailControl), false, false);
                }
                #endregion

                #region order detail folder
                /// if the name of the text contains a . it means it is an extension
                if ((bool)Invoke(new CheckIsCurrentTabAFile(CurrentDetailHasLocalFiles)))
                {
                    Invoke(new UpdateChangeOrderDetailFolder(ChangeOrderDetailFileControl), true);
                }
                else
                {
                    Invoke(new UpdateChangeOrderDetailFolder(ChangeOrderDetailFileControl), false);
                }
                #endregion

                #region status done entry
                if (toolStripStatusLabelMain.Text != "Done")
                {
                    updateStatusToDone -= 1;
                }
                else
                {
                    updateStatusToDone = 5;
                }

                if (updateStatusToDone < 0)
                {
                    /// we are done
                    Invoke(new ToolStripStatusLabelTextDelegate(UpdateStripStatusLableText), "Done");
                }
                #endregion

                /// we wait a little before doing this again
                Thread.Sleep(500);
            }
        }

        #endregion
        #region open site
        /// <summary>
        /// Opens the site management screen
        /// </summary>
        private void OpenSiteManagement()
        {
            _formSiteManagement = new FormSiteManagement(_zetaManager.GetSiteList());
            _formSiteManagement.FormClosing += new FormClosingEventHandler(_formSiteManagement_FormClosing);
            _formSiteManagement.ShowDialog(this);
        }
        #endregion
        #region closing
        /// <summary>
        /// When we are closing the application we need
        /// to make sure we stop the download thread
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosing(CancelEventArgs e)
        {
            if (_timeTicker != null)
            {
                /// if our timeTicker is alive kill it.
                if (_timeTicker.IsAlive)
                {
                    _timeTicker.Abort();
                }
            }

            if (_zetaManager != null)
            {
                /// if the thread is running it, stop it
                if (_zetaManager.AreThreadsAlive)
                {
                    _zetaManager.AbortAllThreads();
                }
            }

            base.OnClosing(e);
        }
        #endregion
        #region order detail
        #region toolStripButtonSaveAs_Click
        /// <summary>
        /// When we have a file selected we can choose to move it elsewhere
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void toolStripButtonSaveAs_Click(object sender, EventArgs e)
        //{
        //    int fileIndex = -1;
        //    string source = string.Empty;
        //    string destination = string.Empty;

        //    if( tabControlOrderDetail.SelectedTab.Text.Contains('.'))
        //    {
        //        for( int count = 0; count < tabControlOrderDetail.SelectedTab.Controls.Count; count++)
        //        {
        //            string tabName = tabControlOrderDetail.SelectedTab.Name;

        //            fileIndex = Convert.ToInt32(tabName.Substring(tabName.IndexOf('.')+1));

        //            if (tabControlOrderDetail.SelectedTab.Controls[count].ToString().Contains("WebBrowser"))
        //            {
        //                source = ((WebBrowser)tabControlOrderDetail.SelectedTab.Controls[count]).Url.ToString();

        //                /// get it to be not a URL, but a normal file name
        //                source = StringManipulator.GetFilePathFromWebPath(source);

        //                /// we are done
        //                break;
        //            }
        //        }
        //    }

        //    if (source.Length > 0)
        //    {
        //        /// get the save file dialog
        //        SaveFileDialog saveFileDialog = new SaveFileDialog();
        //        saveFileDialog.FileName = source;
        //        switch (saveFileDialog.ShowDialog(this))
        //        {
        //            case DialogResult.OK:
        //            case DialogResult.Yes:
        //                /// get the extension of the source file
        //                string extension = source.Substring(source.IndexOf('.'));

        //                /// get our destination guy now
        //                destination = saveFileDialog.FileName;

        //                /// if we do not have the extension 
        //                /// we add one
        //                if (!destination.EndsWith(extension))
        //                {
        //                    destination += extension;
        //                }

        //                /// now do the moving
        //                if ( _currentOrderManager.MoveFile(fileIndex, source, destination))
        //                {
        //                    /// we have changed a name, time to get updated it
        //                    RefreshOrderFileArea();
        //                }
        //                else
        //                {
        //                    /// did not work give an error message
        //                    MessageBox.Show(this, "Could not move/copy file to new location", "Move/Copy file",
        //                        MessageBoxButtons.OK, MessageBoxIcon.Error);
        //                }
        //                break;
        //        }
        //    }
        //}
        #endregion
        /// <summary>
        /// Clear out the order detail area
        /// </summary>
        private void ClearOrderDetailArea()
        {
            /// clear out the current entry
            toolStripTextBoxCurrentOrderNumber.Text = string.Empty;

            /// clear all the rows
            dataGridViewOrderDetail.Rows.Clear();

            try
            {
                pictureBoxPreview.Image = new Bitmap(@"Resources\NoImage.jpg");
            }
            catch
            {
            }
        }
        /// <summary>
        /// Get order details into the area
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="orderId"></param>
        private void RefreshOrderDetailArea()
        {
            ClearOrderDetailArea();

            bool translationHasChanged = false;

            /// get the translation table
            string fileContents;
            using (StreamReader sr = new StreamReader("TranslationDetail.xml"))
            {
                fileContents = sr.ReadToEnd();
            }
                       
            /// get x translation item
            XElement xTranslation = new XElement("TranslationDetail");

            if (fileContents.Length > 0)
            {
                xTranslation = XElement.Parse(fileContents);
            }

            if (_currentOrderManager != null)
            {
                toolStripTextBoxCurrentOrderNumber.Text = _currentOrderManager.OrderEntry.OrderNumber.ToString();

                /// get the file area ready
                RefreshOrderFileArea();

                /// get the status comboBox ready
                RefreshOrderStatusComboBox();

                XElement xOrderDetail = _currentOrderManager.ToXml();

                foreach (XElement xElement in xOrderDetail.Elements())
                {
                    switch (xElement.Name.ToString())
                    {
                        case "Image":
                        case "File":
                        case "Page":
                            /// we do not do anything, this will be handled later
                            break;
                        case "Field":
                            #region field
                            string fieldName = "FieldName:";
                            if (xElement.Attribute("FieldName") != null)
                            {
                                fieldName += xElement.Attribute("FieldName").Value;
                            }
                            string fieldValue = string.Empty;
                            if (xElement.Attribute("FieldValue") != null)
                            {
                                fieldValue = xElement.Attribute("FieldValue").Value;
                            }

                            dataGridViewOrderDetail.Rows.Add(
                                         fieldName,
                                         fieldValue,
                                         null);
                            #endregion
                            break;
                        default:
                            #region normal entries
                            foreach (XAttribute xAttribute in xElement.Attributes())
                            {
                                if (xAttribute.Value.Length > 0)
                                {
                                    string translatedName = string.Empty;

                                    /// check the translation table
                                    if (xTranslation.Element(xAttribute.Name.ToString()) == null)
                                    {
                                        if (!xAttribute.Name.ToString().Contains(':'))
                                        {
                                            /// the entry was not found, create the entry on the translation
                                            /// so we can update it.
                                            xTranslation.Add(new XElement(xAttribute.Name.ToString(),
                                                new XAttribute("Translation", xAttribute.Name.ToString())));

                                            translationHasChanged = true;
                                        }

                                        translatedName = xAttribute.Name.ToString();
                                    }
                                    else
                                    {
                                        translatedName = xTranslation.Element(xAttribute.Name.ToString()).Attribute("Translation").Value;
                                    }

                                    string value = xAttribute.Value;

                                    if (translatedName == "Status")
                                    {
                                        value = OrderStatusManipulator.FromCommandToLang(value);
                                    }

                                    dataGridViewOrderDetail.Rows.Add(
                                         translatedName,
                                         value,
                                         null);
                                }
                            }
                            #endregion
                            break;
                    }
                }

                /// now get the files
                _currentOrderManager.FetchFileList();
            }
            else
            {
                toolStripTextBoxCurrentOrderNumber.Text = string.Empty;
            }

            if ( (translationHasChanged) && (xTranslation != null))
            {
                using (StreamWriter sw = new StreamWriter("TranslationDetail.xml", false))
                {
                    sw.WriteLine(xTranslation.ToString());
                }
            }

            /// but a wrod in the middle for the user to wait
            RefreshOrderDetailDisplay(false);
        }
        /// <summary>
        /// Gets the current information and display the files on tabs
        /// </summary>
        private void RefreshOrderFileArea()
        {
            bool firstPageDownloaded = false;

            if (_currentOrderManager != null)
            {
                foreach (FileManager fileManager in _currentOrderManager.FileManagerList)
                {
                    if ((fileManager.OrderFileDetailEntry.OrderFileDetailType.FileTypeName == "Page") &&
                        (!firstPageDownloaded) &&
                        (_currentPicturePreviewIndex == -1) &&
                        (fileManager.IsImage))
                    {
                        firstPageDownloaded = true;

                        _currentPicturePreviewIndex = fileManager.OrderFileDetailEntry.FileIndex;

                        /// if the file does not exist localy download it.
                        if (!fileManager.FileExistsLocaly)
                        {
                            SetPicture(PictureChoice.Downloading);
                            fileManager.DownloadFile(false);
                        }
                        else
                        {
                            pictureBoxPreview.Image = fileManager.GetImageThumbnail(pictureBoxPreview.Size.Height, pictureBoxPreview.Size.Width);
                        }
                    }
                    else if (_currentPicturePreviewIndex == fileManager.OrderFileDetailEntry.FileIndex)
                    {
                        if ((fileManager.FileExistsLocaly) && (fileManager.IsImage))
                        {
                            /// this is the file we should be displaying
                            pictureBoxPreview.Image = fileManager.GetImageThumbnail(pictureBoxPreview.Size.Height, pictureBoxPreview.Size.Width);
                        }
                    }

                    List<object> columnItems = new List<object>();

                    /// this will tell me what I need to access the record again
                    string columnNameId = "File_" + fileManager.OrderFileDetailEntry.FileIndex;

                    /// description of the file
                    string description = string.Empty;

                    bool firstItem = true;

                    /// this is the name column the first column.
                    string nameColumn = fileManager.OrderFileDetailEntry.Name;

                    /// get the file xml
                    XElement xFile = XElement.Parse(fileManager.OrderFileDetailEntry.Xml);
                    foreach (XAttribute attribute in xFile.Attributes())
                    {
                        /// if this is a preview image we should be using something else for the name
                        if (attribute.Name == "PreviewImage")
                        {
                            nameColumn = attribute.Value.Substring(attribute.Value.LastIndexOf("-") + 1);
                            nameColumn = "Page " + nameColumn.Substring(0, nameColumn.IndexOf("."));
                        }
                        else if (attribute.Name == "FieldName")
                        {
                            nameColumn = attribute.Value;
                        }

                        if (firstItem)
                        {
                            firstItem = false;
                        }
                        else
                        {
                            description += ",";
                        }

                        description += attribute.Name + ":" + attribute.Value;
                    }

                    columnItems.Add(nameColumn);
                    columnItems.Add(description);
                    /// this way we can connect back to it
                    columnItems.Add(columnNameId);

                    bool duplicateFound = false;

                    for (int rowCount = 0; rowCount < dataGridViewOrderDetail.Rows.Count; rowCount++)
                    {
                        if (dataGridViewOrderDetail.Rows[rowCount].Cells[(int)OrderDetailGridColumns.Id].Value != null)
                        {
                            if (dataGridViewOrderDetail.Rows[rowCount].Cells[(int)OrderDetailGridColumns.Id].Value.ToString() == columnNameId)
                            {
                                dataGridViewOrderDetail.Rows[rowCount].Cells[(int)OrderDetailGridColumns.Name].Value = columnItems[0];
                                dataGridViewOrderDetail.Rows[rowCount].Cells[(int)OrderDetailGridColumns.Value].Value = columnItems[1];
                                //dataGridViewOrderDetail.Rows[rowCount].Cells[2].Value = columnItems[2];
                                duplicateFound = true;
                                break;
                            }
                        }
                    }

                    if (!duplicateFound)
                    {
                        /// add the fileds and button to the system
                        dataGridViewOrderDetail.Rows.Insert(0, columnItems.ToArray());

                        for (int count = 0; count < dataGridViewOrderDetail.Rows[0].Cells.Count; count++)
                        {
                            dataGridViewOrderDetail.Rows[0].Cells[count].Style.ForeColor = Color.Blue;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Stops all the thread running for this order
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonStopDownloadOrderFiles_Click(object sender, EventArgs e)
        {
            /// Stops all the threads running for the current order id
            //_zetaManager.AbortOrderIdThread(_currentOrderManager.OrderId);
        }
        /// <summary>
        /// This will update the order status entry
        /// </summary>
        private void RefreshOrderStatusComboBox()
        {
            /// clear out all the items
            toolStripComboBoxOrderStatus.Items.Clear();

            List<OrderStatus> orderStatusList = _zetaManager.FetchOrderStatusList();

            foreach (OrderStatus orderStatus in orderStatusList)
            {
                /// add the item
                toolStripComboBoxOrderStatus.Items.Add(OrderStatusManipulator.FromCommandToLang(orderStatus.OrderStatusName));

                if (_currentOrderManager.OrderEntry.OrderStatusId == orderStatus.OrderStatusId)
                {
                    toolStripComboBoxOrderStatus.SelectedItem = OrderStatusManipulator.FromCommandToLang(orderStatus.OrderStatusName);
                }
            }

        }
        #endregion
        #region order header 
        /// <summary>
        /// Gets the informatino from the current orders and display
        /// on the OrderHeaderGrid
        /// </summary>
        private void RefreshOrderHeaderGrid()
        {
            List<OrderManager> orderManagerList = _zetaManager.GetSelectedOrderManagerList();

            /// was any item added?
            if (orderManagerList.Count != listViewOrderHeader.Items.Count)
            {
                listViewOrderHeader.SuspendLayout();

                listViewOrderHeader.Items.Clear();

                bool detailOrderEntry = false;

                foreach (OrderManager orderManager in orderManagerList)
                {
                    if (_currentOrderManager != null)
                    {
                        if (orderManager.OrderEntry.OrderId == _currentOrderManager.OrderEntry.OrderId)
                        {
                            detailOrderEntry = true;
                        }
                    }

                    List<string> rowString = new List<string>();
                    rowString.Add(orderManager.OrderEntry.OrderId.ToString());
                    rowString.Add(orderManager.OrderEntry.OrderNumber.ToString());
                    rowString.Add(orderManager.OrderEntry.CreatedBy.ToString());
                    rowString.Add(orderManager.OrderEntry.Created.ToString());
                    rowString.Add(orderManager.OrderEntry.Balance.ToString());
                    rowString.Add(OrderStatusManipulator.FromCommandToLang(orderManager.OrderEntry.OrderStatus.OrderStatusName.ToString()));
                    rowString.Add(orderManager.SiteEntry.SiteName);

                    listViewOrderHeader.Items.Add(new ListViewItem(rowString.ToArray()));
                }

                if (!detailOrderEntry)
                {
                    _currentOrderManager = null;
                    ClearOrderDetailArea();
                }

                listViewOrderHeader.ResumeLayout();
            }

            RefreshOrderHeaderDisplay(false);
        }
        /// <summary>
        /// Go and update one status that is displaying
        /// </summary>
        /// <param name="orderNumber"></param>
        /// <param name="newStatus"></param>
        private void ChangeOrderStatus(int orderNumber, string newStatus)
        {
            for (int count = 0; count < listViewOrderHeader.Items.Count; count++)
            {
                /// if we match the order number we must do something
                if (listViewOrderHeader.Items[count].SubItems[(int)OrderHeaderGridColumns.OrderNumber].Text == orderNumber.ToString())
                {
                    listViewOrderHeader.Items[count].SubItems[(int)OrderHeaderGridColumns.OrderStatus].Text = OrderStatusManipulator.FromCommandToLang(newStatus);
                    break;
                }
            }
        }
        #endregion
        #region site combo box
        /// <summary>
        /// Gets all the sites into the list of check boxes for Site
        /// <returns>True if at least one site was returned</returns>
        /// </summary>
        private bool RefreshSiteCheckListBox()
        {
            /// if there is at least one site we will
            /// return a true.
            bool thereIsAtLeastOneSite = false;

            string entrySelected = string.Empty;

            List<string> checkedItemList = new List<string>();

            for (int count = 0; count < checkedListBoxSite.CheckedItems.Count; count++)
            {
                checkedItemList.Add(checkedListBoxSite.CheckedItems[count].ToString());
            }

            /// clear out the sites
            checkedListBoxSite.Items.Clear();

            List<SiteManager> siteManagerList = _zetaManager.GetSiteManagerList();

            /// get all the site go through them and add them
            foreach (SiteManager siteManager in siteManagerList)
            {
                thereIsAtLeastOneSite = true;

                checkedListBoxSite.Items.Add(siteManager.SiteEntry.SiteName, siteManager.Selected);
            }

            /// re-select items that were already selected
            for (int count = 0; count < checkedListBoxSite.Items.Count; count++)
            {
                foreach( string selectedItem in checkedItemList )
                {
                    /// are they the same, if yes select them
                    if (selectedItem == checkedListBoxSite.Items[count].ToString())
                    {
                        checkedListBoxSite.SetItemChecked(count, true);
                        checkedListBoxSiteItemCheck(selectedItem,CheckState.Checked);
                    }
                }
            }

            /// we got items selected, we need to refresh 
            /// it
            if (checkedItemList.Count > 0)
            {
                RefreshOrderHeaderDisplay(true);
                RefreshOrderHeaderGrid();
            }

            return thereIsAtLeastOneSite;
        }
        /// <summary>
        /// When we click for a new item to be site to be used we come in here 
        /// to make the change
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void toolStripComboBoxSite_SelectedIndexChanged(object sender, EventArgs e)
        {
            //_zetaManager.SiteList = _zetaManager.FetchSite(toolStripComboBoxSite.SelectedItem.ToString());

            ///// now get all the orders we have for this item
            //RefreshOrderHeaderGrid();

            ///// if there is something selected go ahead and enable the download button
            //if (toolStripComboBoxSite.SelectedItem.ToString().Length > 0)
            //{
            //    toolStripButtonDownload.Enabled = true;
            //}
            //else
            //{
            //    toolStripButtonDownload.Enabled = false;
            //}
        }
        #endregion        
        #region format main load
        private void FormMain_Load(object sender, EventArgs e)
        {
            /// this means the system is not really up, go ahead and
            /// kill the application.
            if (_zetaManager == null)
            {
                this.Close();
            }
        }
        #endregion
        #endregion
    }
}
